//
//  AVAssetViewController.m
//  BTAVEditor
//
//  Created by TMAC on 2020/1/9.
//  Copyright © 2020 XMac. All rights reserved.
//

#import "AVAssetViewController.h"
#import "BTAVPlayerView.h"

@interface AVAssetViewController ()
@property (weak, nonatomic) IBOutlet BTAVPlayerView *playerView;
@property (weak, nonatomic) IBOutlet UIImageView *playImage;
@property (weak, nonatomic) IBOutlet UISlider *controlSlider;

@property (strong, nonatomic) AVURLAsset *currentAsset;

@property (strong, nonatomic) id periodicTimeObserver;

@property (assign, nonatomic) double totalTime;

@property (assign, nonatomic) BOOL isSeeking;


@property (weak, nonatomic) IBOutlet UIView *thumbnailView;

@end

@implementation AVAssetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configData];
    
}


-(void)dealloc{
    if (self.periodicTimeObserver) {
        [self.playerView.player removeTimeObserver:self.periodicTimeObserver];
        self.periodicTimeObserver = nil;
    }
}

-(void)configData{
    NSURL *localUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"xiongmao" ofType:@"mp4"]];
    self.currentAsset = [[AVURLAsset alloc]initWithURL:localUrl options:nil];
    
    __weak AVAssetViewController *ws = self;
    NSArray *keys = @[@"playable",@"duration"];
    
    [self.currentAsset loadValuesAsynchronouslyForKeys:keys completionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            for (NSString *key in keys) {
                NSError *error = nil;
                AVKeyValueStatus keyStatus = [ws.currentAsset statusOfValueForKey:key error:&error];
                if (keyStatus == AVKeyValueStatusFailed) {
                    NSLog(@"error (%@)", [[error userInfo] objectForKey:AVPlayerItemFailedToPlayToEndTimeErrorKey]);
                    return;
                }
            }
            if (!ws.currentAsset.playable) {
                return;
            }
            
            AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:ws.currentAsset];
            
            ws.playerView.player = [AVPlayer playerWithPlayerItem:item];
            ((AVPlayerLayer *)self.playerView.layer).videoGravity = AVLayerVideoGravityResizeAspectFill;
            AVAudioSession *session = [AVAudioSession sharedInstance];
            [session setCategory:AVAudioSessionCategoryPlayAndRecord
                     withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
                           error:nil];
            
            ws.totalTime = CMTimeGetSeconds(ws.currentAsset.duration);
            //周期回调
            ws.periodicTimeObserver = [ws.playerView.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                if (ws.controlSlider.tracking) {
                    return;
                }
                double current = CMTimeGetSeconds(time);
                ws.controlSlider.value = current/ws.totalTime;
                NSLog(@"当前已经播放%.2fs.",current);
                if (current >= ws.totalTime) {
                    CMTime time = CMTimeMakeWithSeconds(0, item.duration.timescale);
                    [ws.playerView.player seekToTime:time];
                    ws.playImage.hidden = NO;
                }
            }];
            
            [ws loadThumbnail];
        });
    }];
}

-(void)configUI{
    
}

- (IBAction)playAction:(UITapGestureRecognizer *)sender {
    if (self.playerView.player.rate == 0) {
        [self.playerView play];
        [self.playImage setHidden:YES];
    }else{
        [self.playerView pause];
        [self.playImage setHidden:NO];
    }
}



- (IBAction)silderAction:(UISlider *)sender {
    [self.playerView.player seekToTime:CMTimeMake(sender.value * self.totalTime, 1.0) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
}

-(void)loadThumbnail{
    AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:self.currentAsset];
    NSMutableArray *times = @[].mutableCopy;
    __block int count = 10;
    for (int i = 0; i < count; i++) {
        [times addObject:[NSValue valueWithCMTime:CMTimeMake(self.currentAsset.duration.value * i / 10, self.currentAsset.duration.timescale)]];
    }
    
    __weak AVAssetViewController *ws = self;
    NSMutableArray *images = @[].mutableCopy;
    [imageGenerator generateCGImagesAsynchronouslyForTimes:times completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        UIImage *im = [UIImage imageWithCGImage:image];
        [images addObject:im];
        if (--count == 0) {
            [ws attachThumbnail:images];
        }
    }];
}

-(void)attachThumbnail:(NSArray<UIImage *> *)images{
    dispatch_async(dispatch_get_main_queue(), ^{
        float sw = CGRectGetWidth([UIScreen mainScreen].bounds) - 32;
           for (int i = 0; i < images.count; i++) {
               UIImageView *imageView = [[UIImageView alloc]initWithImage:images[i]];
               [imageView setFrame:CGRectMake(sw/10 * i, 0, sw/10, 50)];
               [self.thumbnailView addSubview:imageView];
           }
    });
}

@end
